package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.config.AlipayConfig;
import com.qf.feign.OrderService;
import com.qf.vo.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.alipay.api.AlipayConstants.CHARSET;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/24/9:33
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping("/ali")
public class payController {
    @Autowired
    private OrderService orderService;
     @RequestMapping("/pay")
    public void pay(String oid, HttpServletResponse httpResponse) throws AlipayApiException {
         log.debug("=================");
        log.debug("oid:{}",oid);
         //获得初始化的AlipayClient
         AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
         //设置请求参数
         AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
         alipayRequest.setReturnUrl(AlipayConfig.return_url);
         alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
         //获取订单信息
         Order order = orderService.getOrderByOid(oid);
         //商户订单号，商户网站订单系统中唯一订单号，必填
         String out_trade_no = oid;
         //付款金额，必填
         double total_amount =order.getTotalPrice().doubleValue();
         //订单名称，必填
         String subject = order.getSubject();
         //商品描述，可空
         String body =order.getBody();
         String timeout_express="1m";
         alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                 + "\"total_amount\":\""+ total_amount +"\","
                 + "\"subject\":\""+ subject +"\","
                 + "\"body\":\""+ body +"\","
                 + "\"timeout_express\t\":\""+ timeout_express	 +"\","
                 + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

         //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
         //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
         //		+ "\"total_amount\":\""+ total_amount +"\","
         //		+ "\"subject\":\""+ subject +"\","
         //		+ "\"body\":\""+ body +"\","
         //		+ "\"timeout_express\":\"10m\","
         //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
         //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

         //请求
         String result = null;
         try {
             result = alipayClient.pageExecute(alipayRequest).getBody();
             httpResponse.setContentType( "text/html;charset="+AlipayConfig.charset);
             httpResponse.getWriter().write(result); //直接将完整的表单html输出到页面
             httpResponse.getWriter().flush();
             httpResponse.getWriter().close();
         } catch (IOException e) {
             e.printStackTrace();
         }

         //输出
         log.debug("result:{}",result);
    }
   @PostMapping("/updateStatus")
    public void updateStatus(HttpServletRequest request){
       log.debug("已支付完成,通知商家修改订单状态..........");
       Map<String, String> paramsMap = new HashMap<>()  ;//将异步通知中收到的所有参数都存放到 map 中
       Map<String, String[]> parameterMap = request.getParameterMap();
       Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
       for (Map.Entry<String, String[]> entry : entries) {
           String[] value = entry.getValue();
           String key = entry.getKey();
           log.debug("key:{},value:{}",key, Arrays.toString(value));
           paramsMap.put(key,value[0]);
       }
       try {
           boolean  signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);  //调用SDK验证签名
           if (signVerified){
               // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
              log.debug("验签成功...");
               String status = paramsMap.get("trade_status");
               if("TRADE_SUCCESS".equals(status)){
                   //修改订单状态
                   String out_trade_no = paramsMap.get("out_trade_no");
                   orderService.updateOrderStatus(out_trade_no,2);
                   log.debug("修改订单状态成功......");
               }

           } else {
               // TODO 验签失败则记录异常日志，并在response中返回failure.
               log.error("验签失败.......");
           }
       } catch (AlipayApiException e) {
           e.printStackTrace();
       }

   }
}
